package cn.com.callback;

import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import cn.com.kh.KHDBConfig;
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB;
import cn.com.kh.signUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat;

/**
 *
 * @Title: 平安短链映射集中作业平台短链查询接口
 */

public class apiGetWXminipURL implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetWXminipURL.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        long startTimet = System.currentTimeMillis();
        StringBuffer logRemark = new StringBuffer();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        logRemark.append("获取数据源耗时:" + (System.currentTimeMillis() - startTimet).toString() + System.getProperty("line.separator"));

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        String WXCallBackURL = KHDBConfig.getAPIURL(eliteBean, "WXCallBackURL") + "/ngsapitask_pa/file/apiFileProxy?fileurl=" + KHDBConfig.getAPIURL(eliteBean, "NGS-InnserDomain") + "fs/get?file=";

        try {
            //解析Json
            JSONObject inJson = JSONObject.fromObject(inData);

            String apiid = inJson.getString("apiid");
            String apikey = KHDBConfig.getSignInfo(eliteBean, apiid);
            String data = inJson.getString("data");
            String timestamp = inJson.getString("timestamp");
            String sendsign = inJson.getString("sign");

            String signBefore = "apiid=" + apiid + "&apikey=" + apikey + "&timestamp=" + timestamp + "&data=" + data + "";
            String signAfter = "";
            try {
                signAfter = Util.getMD5Str(signBefore);
                System.out.println("MD5:" + signAfter);
            } catch (Exception e) {
                signAfter = "";
                log.warn("签名异常:");
            }
            log.debug("签名信息:" + signAfter);

            if (KHUtil.isNull(signAfter) || signAfter != sendsign) {
                result.put("code", -3);
                result.put("msg", "签名信息错误");
                sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "签名信息错误", "000116", "开发", "1");
            } else {

                if (!KHUtil.isNull(data)) {
                    startTimet = System.currentTimeMillis();
                    String selectSQL = '''Select Staff_Id As Rec_Guid,
                                           Stringfield5 As Pa_Url,
                                           1 As Type,
                                           If(Modifieddate Is Null, If(Createddate Is Null, Now(), Createddate), Modifieddate) As Createddate
                                      From Staff
                                     Where (Wechat_Url = ? Or Right(?, Length(Wechat_Url)) = Wechat_Url) And Workstatus = 'ONLINE' And Wechat_Url != '' And Wechat_Url Is Not Null
                                    Union All
                                    Select Poster_Guid As Rec_Guid,
                                           Poster_Url As Pa_Url,
                                           2 As Type,
                                           If(Createddate Is Null, Now(), Createddate) As Createddate
                                      From Poster_Batch
                                     Where Batch_State = '已完成'
                                       And (Poster_Wechat_Url = ? Or Right(?, Length(Poster_Wechat_Url)) = Poster_Wechat_Url) And Poster_Wechat_Url != '' And Poster_Wechat_Url Is Not Null
                                     Order By Type, Createddate Desc Limit 1''';
                    List<Map<String, Object>> selectCus = jt.queryForList(selectSQL, data, data, data, data);
                    log.debug("通过平安短链获取海报信息..." + selectCus.toString());
                    logRemark.append("获取平安短链获取海报耗时:" + (System.currentTimeMillis() - startTimet).toString() + System.getProperty("line.separator"));
                    if (selectCus.size() > 0) {

                        String API_OuterDomain = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain");
                        String Staff_Id = selectCus.get(0).get("Rec_Guid");
                        String imageArr = selectCus.get(0).get("Pa_Url");
                        String imageType = selectCus.get(0).get("Type");

                        if (!KHUtil.isNull(imageArr)) {
                            startTimet = System.currentTimeMillis();
                            String Poster_Url = WXCallBackURL + imageArr;

                            String Rec_Guid = KHUtil.getRandomString(36).toUpperCase();
                            log.debug("编号: " + Rec_Guid + " 被发送对象: " + Staff_Id + " imageArr: " + imageArr + " 完整图片URL: " + Poster_Url);

                            // 调用获取短链接
                            JSONObject postBody = new JSONObject();
                            postBody.put("path", "/pages/index/index");
                            postBody.put("is_expire", true);
                            postBody.put("expire_type", 1);
                            postBody.put("expire_interval", 30);

                            postBody.put("query", "recid=" + Rec_Guid + "&expand=" + imageType); // imageType 1坐席 2批量 3直接发送

                            String postResult = Util.doHttpPost(API_OuterDomain + "/apiWXMiniPURL", postBody.toString(), "UTF-8", 12000, 0);
                            logRemark.append("获取海报微信短链接耗时:" + (System.currentTimeMillis() - startTimet).toString() + System.getProperty("line.separator"));

                            JSONObject postResultJson = JSONObject.fromObject(postResult);

                            int errcode = postResultJson.getInt("errcode");

                            if (errcode == 0) {
                                startTimet = System.currentTimeMillis();
                                // 获取短链接成功
                                String url_link = postResultJson.getString("url_link");

                                log.debug("短链接地址：" + url_link);

                                String insertSQL = '''Insert Into Wx_Shortenurl_Map
                                                  (Recid, Staff_Id, Pa_Surl, Wx_Surl, Pic_Url_Arr, Create_Time)
                                                Values
                                                  (?, ?, ?, ?, ?, Now())''';

                                int insertNum = jt.update(insertSQL, Rec_Guid, Staff_Id, data, url_link, Poster_Url);

                                log.debug("重定向信息DB操作完成：" + Rec_Guid + " 成功 操作数据：" + insertNum);
                                logRemark.append("记录微信短链接耗时:" + (System.currentTimeMillis() - startTimet).toString() + System.getProperty("line.separator"));


                                result.put("code", 1);
                                result.put("msg", "映射地址处理成功");
                                result.put("data", url_link);

                            } else {

                                result.put("code", -3);
                                result.put("msg", "未获取到短链接信息");

                            }
                        } else {
                            result.put("code", -4);
                            result.put("msg", "集中作业系统短链接StaffPic Lost");

                            /*
                            000281 颜滕
                            000277 林梓敏
                            000278 曹先佩
                            000311 黄钰雯
                            000328 彭寒冰
                            803200 胡婷婷
                            */
                            sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "集中作业系统短链接对于的二维码图片未配置或异常(" + data + ")", "000116", "开发", "0");
                            sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "集中作业系统短链接对于的二维码图片未配置或异常(" + data + ")", "000281", "颜滕", "0");
                            sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "集中作业系统短链接对于的二维码图片未配置或异常(" + data + ")", "000277", "林梓敏", "0");
                            sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "集中作业系统短链接对于的二维码图片未配置或异常(" + data + ")", "000278", "曹先佩", "0");
                            sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "集中作业系统短链接对于的二维码图片未配置或异常(" + data + ")", "000311", "黄钰雯", "0");
                            sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "集中作业系统短链接对于的二维码图片未配置或异常(" + data + ")", "000328", "彭寒冰", "0");
                            sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "集中作业系统短链接对于的二维码图片未配置或异常(" + data + ")", "803200", "胡婷婷", "0");

                        }

                    } else {
                        result.put("code", -2);
                        result.put("msg", "当前集中作业系统未维护改短链接的信息");

                        sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "当前集中作业系统未维护改短链接的信息(" + data + ")", "000116", "开发", "1");
                        sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "当前集中作业系统未维护改短链接的信息(" + data + ")", "000281", "颜滕", "1");
                        sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "当前集中作业系统未维护改短链接的信息(" + data + ")", "000277", "林梓敏", "1");
                        sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "当前集中作业系统未维护改短链接的信息(" + data + ")", "000278", "曹先佩", "1");
                        sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "当前集中作业系统未维护改短链接的信息(" + data + ")", "000311", "黄钰雯", "1");
                        sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "当前集中作业系统未维护改短链接的信息(" + data + ")", "000328", "彭寒冰", "1");
                        sendMsg_Note(eliteBean, "集中作业系统短链接异常⚠", "当前集中作业系统未维护改短链接的信息(" + data + ")", "803200", "胡婷婷", "1");

                    }

                } else {
                    result.put("code", -1);
                    result.put("msg", "入参中data字段为空");
                }
            }
            log.info("调用处理结果：" + result.toString());

        } catch (Exception e) {
            log.error("", e);
            result.put("code", -1);
            result.put("msg", "数据处理错误");
        } finally {
            toDB(eliteBean, "dataSource", "PA企微短码", "apiGetWXminipURL", inData, result.toString(), (System.currentTimeMillis() - startTime).toString(), logRemark.toString());
        }

        return result.toString();
    }

    // 记录日志到系统DB
    public static void toDB(final EliteBean eliteBean, final String dataSource, final String Name, final String Type, final String Request, final String Response, final String Consume, final String Remark) {
        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            String Log_Guid = UUID.randomUUID().toString();
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final String nowTime = simpleDateFormat.format(date);

            String updateSQL = "Insert Into Ws_Interface_Log_qw (Log_Guid, Name, Time, Type, Request, Response, Consume, Remark) Values (?, ?, ?, ?, ?, ?, ?, ?)";

            jt.update(updateSQL, Log_Guid, Name, nowTime, Type, Request, Response, Consume, Remark);

        } catch (Exception e) {
            log.error("LogToDB Exception:", e);
        }
    }

    public static boolean sendMsg_Note(EliteBean eliteBean, String Subject, String Content, String Staffid, String StaffName, String Priority) {

        String note_Guid = KHUtil.getRandomString(36);
        String Msg_Note_Staff = "Insert Into Msg_Note_Staff (Msgid, Staffid, Readtime, Flag, Replied, Deleted) Values ('" + note_Guid + "', '" + Staffid + "', Null, 0, 0, 0)";
        String Msg_Note = "Insert Into Msg_Note (Id, Subject, Priority, Receiver, Createdby, Createdtime, Deleted, Content) Values ('" + note_Guid + "', '" + Subject + "', '" + Priority + "', '" + StaffName + "', 'SELITE', Now(), 0, '" + Content + "</br></br><span style=\"color:red\">⚠️本便签由系统自动发出，请勿直接回复！</span>')";
        eliteBean.update(Msg_Note_Staff, "dataSource");
        eliteBean.update(Msg_Note, "dataSource");

    }
}